﻿<%@ Page Language="VB" %>
<%@ Import Namespace="ICSharpCode.SharpZipLib" %>
<script runat="server" language="VB">
    ' $Id: test.aspx 13 2009-12-11 16:09:26Z taoyagi $
    
    ''' <summary>
    ''' セキュリティ情報の取得
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub TestClick(ByVal sender As Object, ByVal e As System.EventArgs)
	Results.Text = "" _
		& " [ " & String.Format("{0:D}", Now) _
		& " / " & String.Format("{0:hh:mm:ss}", Now) _
		& " / " & String.Format("{0}", My.User.Name) _
		& " / " & String.Format("{0}", My.Request.UserHostAddress) _
		& " / " & String.Format("{0}", My.Request.ClientCertificate("SUBJECTCN")) _
		& " / " & String.Format("{0}", My.Request.ClientCertificate("SUBJECTEMAIL")) _
		& " / " & String.Format("{0}", My.Request.ClientCertificate("ValidUntil")) _
		& " ] "
    End Sub

    ''' <summary>
    ''' ハッキングダウンロード
    ''' </summary>
    ''' <param name="path"></param>
    ''' <remarks></remarks>
    Protected Sub Download(ByVal path As String)
        Try
            'ハッキングダウンロード
            If IO.File.Exists(path) Then
                Response.ContentType = "application/octet-stream"
                Response.AddHeader("Content-Disposition", "attachment; filename=" + IO.Path.GetFileName(path))
                Response.Flush()
                Response.WriteFile(path)
                Response.End()
            Else
                Throw New Exception("ファイルが無い")
            End If
        Catch ex As Exception
            'エラーが出たらファイルの場所を表示
            Results.Text = Request.PhysicalApplicationPath
        End Try
    End Sub

    ''' <summary>
    ''' 環境情報表示
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim c As HttpCookie = Request.Cookies("frTestSecureToken")
        If (Not c Is Nothing) AndAlso c.Value = "e587ac01ad3546ab1cc07cb1e2cfe5fdf3f623d4" Then
            dotNetFrameworkVersion.Text = String.Format(".NET Framework version {0}", System.Environment.Version)
            AppUser.Text = String.Format("Proccess user {0}", System.Environment.UserDomainName)
            OSVersion.Text = String.Format("OS version {0}", System.Environment.OSVersion)
        Else
            '一般からのアクセスは禁止
            Results.Text = "アクセス禁止"
            Button1.Enabled = False
            Button2.Enabled = False
            Button3.Enabled = False
            DropDownList1.Enabled = False
            FileUpload1.Enabled = False
            FileUpload2.Enabled = False
        End If
    End Sub

    Protected Sub DropDownList1_Init(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ddl As DropDownList = sender
        Dim di As IO.DriveInfo
        
        ddl.Items.Add("ドライブを選択してください。")
        
        Dim c As HttpCookie = Request.Cookies("frTestSecureToken")
        If (Not c Is Nothing) AndAlso c.Value = "e587ac01ad3546ab1cc07cb1e2cfe5fdf3f623d4" Then
            For Each di In My.Computer.FileSystem.Drives
                ddl.Items.Add(di.Name)
            Next
            ddl.Items.Add("D:\data\WebSite\web\")
            ddl.Items.Add(My.Request.PhysicalApplicationPath)
        Else
            '一般からのアクセスは禁止
            Results.Text = "アクセス禁止"
        End If
    End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ddl As DropDownList = sender
        SetList(ddl.SelectedItem.Text)
    End Sub
    
    Protected Sub SetList(ByVal path As String)
        Label2.Text = "？"
        Dim d As String
        Dim t As New Data.DataTable
        t.Columns.Add("Path")
        t.Columns.Add("Text")
        t.Columns.Add("Command")
        
        Try
            For Each d In My.Computer.FileSystem.GetDirectories(path)
                t.Rows.Add(New String() {d, ">>", "Go"})
            Next
            For Each d In My.Computer.FileSystem.GetFiles(path)
                t.Rows.Add(New String() {d, "Download", "Get"})
            Next
            Label2.Text = path
        Catch ex As Exception
            t.Rows.Add(New String() {"!エラー"})
            Label2.Text = "!エラー"
        End Try
        
        List1.DataSource = t
        List1.DataBind()
    End Sub

    Protected Sub List1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
        Select Case e.CommandName
            Case "Go"
                SetList(e.CommandArgument)
            Case "Get"
                Download(e.CommandArgument)
        End Select
    End Sub

    ''' <summary>
    ''' 一括ダウンロード
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim path As String = Label2.Text

        Response.ContentType = "application/octet-stream"
        Response.AddHeader("Content-Disposition", "attachment; filename=" + path.ToLower.Replace("\", ".").Replace(":.", "_") + ".zip")
        Response.Flush()
        
        If IO.Directory.Exists(path) Then
            Using ms As New IO.MemoryStream()
                DownloadPack(path, Response.OutputStream)
            End Using
        End If
        Response.End()

    End Sub
    
    ''' <summary>
    ''' 一括アップロード
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If IO.Directory.Exists(Label2.Text) AndAlso FileUpload1.FileBytes.Length > 0 Then
            Dim tempFile As String = IO.Path.GetTempFileName
            FileUpload1.SaveAs(tempFile)
            UploadPack(tempFile, Label2.Text)
            IO.File.Delete(tempFile)
        End If
    End Sub

    ''' <summary>
    ''' 指定パス以下のファイルをストリームに読み込む
    ''' </summary>
    ''' <param name="path"></param>
    ''' <param name="st"></param>
    ''' <remarks></remarks>
    Protected Sub DownloadPack(ByVal path As String, ByVal st As IO.Stream)
        '圧縮するパス 
        Dim sourceDirectory As String = path
        '圧縮するファイルのフィルタ 
        Dim fileFilter As String = ""
        '圧縮するディレクトリのフィルタ 
        Dim directoryFilter As String = ""
        
        'サブディレクトリも圧縮
        Dim recurse As Boolean = True

        'FastZipオブジェクトの作成 
        Dim fastZip As New Zip.FastZip()
        '空のフォルダも書庫に入れるか。デフォルトはfalse 
        fastZip.CreateEmptyDirectories = True
        
        'ZIP64を使うか。デフォルトはDynamicで、状況に応じてZIP64を使う 
        '（大きなファイルはZIP64でしか圧縮できないが、対応していないアーカイバもある） 
        fastZip.UseZip64 = Zip.UseZip64.Dynamic

        'パスワードを設定
        'fastZip.Password = "password"

        '書庫を送信（フィルターは正規表現）
        fastZip.CreateZip(st, sourceDirectory, recurse, fileFilter, directoryFilter)
    End Sub
    
    ''' <summary>
    ''' 指定パス以下にZip展開
    ''' </summary>
    ''' <param name="zipfile"></param>
    ''' <param name="path"></param>
    ''' <remarks></remarks>
    Protected Sub UploadPack(ByVal zipfile As String, ByVal path As String)
        '展開したファイルを保存するフォルダ（存在しないと作成される） 
        Dim targetDirectory As String = path
        '展開するファイルのフィルタ 
        Dim fileFilter As String = ""

        'FastZipオブジェクトの作成 
        Dim fastZip As New Zip.FastZip()
        '属性を復元するか。デフォルトはfalse 
        fastZip.RestoreAttributesOnExtract = True
        'ファイル日時を復元するか。デフォルトはfalse 
        fastZip.RestoreDateTimeOnExtract = True
        '空のフォルダも作成するか。デフォルトはfalse 
        fastZip.CreateEmptyDirectories = True

        'パスワード 
        'パスワードが設定されている書庫をパスワードを指定せずに展開しようとすると、 
        '　例外ZipExceptionがスローされる 
        'fastZip.Password = "password"
        
        'ZIP書庫を展開する 
        Try
            fastZip.ExtractZip(zipfile, targetDirectory, fileFilter)
        Catch ex As Zip.ZipException
            Throw ex
        End Try
    End Sub

    ''' <summary>
    ''' 単一ファイルアップロード
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If IO.Directory.Exists(Label2.Text) AndAlso FileUpload2.FileBytes.Length > 0 Then
            FileUpload2.SaveAs(Label2.Text & "\" & FileUpload2.FileName)
            SetList(Label2.Text)
        End If
    End Sub
</script>

<html>
<head>
    <title>スクリプトサービス</title>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        バックアップ＆リストア</h1>
    <asp:Label ID="dotNetFrameworkVersion" runat="server"></asp:Label><br />    
    <asp:Label ID="AppUser" runat="server"></asp:Label><br />    
    <asp:Label ID="OSVersion" runat="server"></asp:Label><br />    
    <br />
    <asp:Button ID="TEST"  runat="server" Text="テスト" OnClick="TestClick" />
    <asp:Label ID="Results" runat="server"></asp:Label>
    <p>
        ドライブ選択：<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
            oninit="DropDownList1_Init" 
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList>
    </p>
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        <asp:DataList runat="server" ID="List1" 
        onitemcommand="List1_ItemCommand">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Path") %>'></asp:Label>
                <asp:LinkButton ID="LinkButton1" runat="server" 
                    CommandArgument='<%# Bind("Path") %>' Text='<%# Bind("Text") %>' CommandName='<%# Bind("Command") %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:DataList>
    <p>
        ファイルアップロード<br />
        <asp:FileUpload ID="FileUpload2" runat="server" />
        　<asp:Button ID="Button3" runat="server" Text="上記の場所に上書き保存" 
            onclick="Button3_Click" />
    </p>
    <hr />
    <p>
        Zip一括ダウンロード　<asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="上記ファイル一覧を取得" />
    </p>
    <p>
        Zip一括アップロード<br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        　<asp:Button ID="Button2" runat="server" Text="上記の場所に展開して上書き保存" 
            onclick="Button2_Click" />
    </p>
    <p>
        &nbsp;</p>
    <p>
        <a href="test.html">TOP</a></p>
    </form>
    </body>
</html>
